package cultu.customer.service.impl;

import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

import cultu.core.message.JpqlParameter;
import cultu.customer.message.Offer;
import cultu.customer.message.OfferCriteria;
import cultu.customer.message.OfferList;
import cultu.customer.message.OfferScenario;
import cultu.customer.service.OfferManager;
import cultu.customer.service.OfferService;

/**
 * Implementation.
 * @author Marc-Antoine
 *
 */
public class OfferServiceImpl implements OfferService
{
  
  /**
   * Offer manager.
   */
  private OfferManager offerManager;

  /**
   * Setter.
   * @param offerManager the offer manager to set.
   */
  public void setOfferManager(OfferManager offerManager)
  {
    this.offerManager = offerManager;
  }



  /**
   * {@inheritDoc}
   */
  @Transactional
  public OfferList actualOffers()
  {
    
    // HQL builder.
    final StringBuilder hqlBuilder = new StringBuilder("Select o From Offer o Where o.startDate <= :today And o.endDate >= :today ");
    
    // Parameter.
    final JpqlParameter parameter = new JpqlParameter();
    parameter.setAlias("today");
    parameter.setValue(new Date());
    
    // Criteria.
    final OfferCriteria criteria = new OfferCriteria();
    criteria.setJpqlQuery(hqlBuilder.toString());
    criteria.getParameter().add(parameter);
    
    return offerManager.findOffers(null, new OfferScenario(), criteria);
    
  }

  /**
   * {@inheritDoc}
   */
  @Transactional
  public Offer actualOffer(Long productId)
  {
    // HQL builder.
    final StringBuilder hqlBuilder = new StringBuilder("Select o From Offer o Where o.startDate <= :today And o.endDate >= :today ");
    hqlBuilder.append("And o.product.hjid = :productId ");
    
    // Parameter.
    final JpqlParameter parameter = new JpqlParameter();
    parameter.setAlias("today");
    parameter.setValue(new Date());
    
    final JpqlParameter parameter2 = new JpqlParameter();
    parameter2.setAlias("productId");
    parameter2.setValue(productId);
    
    // Criteria.
    final OfferCriteria criteria = new OfferCriteria();
    criteria.setJpqlQuery(hqlBuilder.toString());
    criteria.getParameter().add(parameter);
    criteria.getParameter().add(parameter2);

    
    final OfferList offerList = offerManager.findOffers(null, new OfferScenario(), criteria);
    
    if (offerList != null && !offerList.getOffers().isEmpty()) {
      return offerList.getOffers().get(0);
    } else {
      return null;
    }
  }

}
